<?php

namespace app\admin\controller;

//附件管理
class Attach extends Auth
{


    //配置管理
    public function index(){
        //按关键词查询
        $keyword=input('keyword','','trim');
        if($keyword)$map[] = ['filename','like','%'.$keyword.'%'];

        //时间段查询
        $map=$this->condtime($map);

        $pagesize=20;
        $list = db("attach")->where($map)->order("id desc")->paginate($pagesize,false,['query'=>request()->param()]);

        //状态
        $reviewary=array(-1=>'全部',1=>'启用',0=>'禁用');
        return view("",compact(['list','reviewary','keyword','type','group','state','pages']));
    }


    /**
     * 删除附件
     * @param int $id
     */
    public function del($id){
        if(!$id)return false;
        $this->delfile($id);

        $this->success('删除成功');
    }


    //删除文件
    private function delfile($id){
        $where['id']=$id;
        $att=db('attach');
        $res = $att->where($where)->find();
        if($res){
            $filename ='.'.$res['path'];
            $att->where($where)->delete();
            $ext = getImageFormat($filename);
            unlink($filename);

            //是图片,需要删除缩略图
            if(0==$res['module']){
                $thumb_img=config('THUMB_IMG');
                if(empty($thumb_img)){
                    $w=400;
                    $h=300;
                    $save_path = $filename.'_'.$w.'x'.$h.'.'.$ext;
                    if(is_file($save_path))unlink($save_path);
                }else{
                    //根据配置生成多张缩略图片
                    foreach($thumb_img as $val){
                        $_format=explode('x', $val);
                        $save_path = $filename.'_'.$_format[0].'x'.$_format[1].'.'.$ext;
                        if(is_file($save_path))unlink($save_path);
                    }
                }

            }
        }
    }


    //批量删除文件
    public function delall(){
        $id = array_unique((array)input('id',0));
        if(empty($id))$this->error('请选择要操作的数据!');

        foreach($id as $vo)$this->delfile($vo);
        $this->success('删除成功');
    }


}
